package v1

import (
	"fmt"
	"usplatformserver/global"
	"usplatformserver/internal/model"
	"usplatformserver/internal/service"
	"usplatformserver/pkg/app"
	"usplatformserver/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type GetDisplayConfig struct{}

// 获取显示配置结果
type GetDisplayConfigRet struct {
	Cfg *model.DisplayConfig
	Err error
}

func NewGetDisplayConfig() GetDisplayConfig {
	return GetDisplayConfig{}
}

// @Summer 获取显示配置
// @Produce json
// @Param organType query int true "检查部位"
// @Success 200 {object} model.GetDisplayConfigSwaggerSuccess "成功"
// @Failure 400 {object} errcode.Error "请求错误"
// @Failure 500 {object} errcode.Error "内部错误"
// @Router /api/v1/display/config [get]
func (t *GetDisplayConfig) GetDisplayConfig(c *gin.Context) {
	getChan := make(chan GetDisplayConfigRet, 1)

	param := service.GetDisplayConfigParam{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, &param)
	if !valid {
		response.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}

	go func() {

		addr := fmt.Sprintf("tcp://%v:%d", global.ZMQSettings.Addr, global.ZMQSettings.Port)
		var ret GetDisplayConfigRet
		svc := service.New(c.Request.Context())
		cfg, err := svc.GetDisplayConfig(addr, *param.OrganType)
		ret.Err = err
		ret.Cfg = cfg
		getChan <- ret
	}()

	for {
		ret := <-getChan
		if ret.Err != nil {
			global.Logger.Infof("svc.GetDisplayConfig failed: %v", ret.Err)
			response := app.NewResponse(c)
			response.ToErrorResponse(errcode.ErrorGetDisplayConfigFail)
			break
		} else {
			response := app.NewResponse(c)
			response.ToResponse(ret.Cfg)
			break
		}
	}
	close(getChan)
}
